﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.Practices.Unity;

namespace ProgrammingSchool.Infrastructure.Factories
{
    public class UnityControllerFactory : DefaultControllerFactory
    {
        private readonly IUnityContainer _container;

        public UnityControllerFactory(IUnityContainer container)
        {
            _container = container;
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            try
            {
                #region Posible exceptions

                if (controllerType == null)
                    throw new ArgumentNullException("controllerType");

                if (!typeof(IController).IsAssignableFrom(controllerType))
                    throw new ArgumentException(string.Format("Type requested is not a controller: {0} controllerType", controllerType));

                #endregion

                return _container.Resolve(controllerType) as IController;
            }
            catch
            {
                return base.GetControllerInstance(requestContext, controllerType);
            }
        }
    }
}